<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Change Material of 3d Model</title>
    <link rel="stylesheet" href="/css/examples.css?ver=1.0.0" />
    <script src="/js/examples.js?ver=1.1.1"></script>
    <script src="/lib/phaser.min.js?ver=3.52.0"></script>
    <script src="/lib/enable3d/enable3d.phaserExtension.0.22.0.min.js"></script>
  </head>

  <body>
    <div id="info-text">Enlighten colors by 10% and added a metallic look.</div>
    <script>
      const { enable3d, Scene3D, Canvas, ExtendedObject3D, THREE } = ENABLE3D

      class MainScene extends Scene3D {
        constructor() {
          super({ key: 'MainScene' })
        }

        init() {
          this.accessThirdDimension()
        }

        create() {
          this.third.warpSpeed('-ground')

          // https://css-tricks.com/snippets/javascript/lighten-darken-color/
          function LightenDarkenColor(col, amt) {
            var usePound = false

            if (col[0] == '#') {
              col = col.slice(1)
              usePound = true
            }

            var num = parseInt(col, 16)

            var r = (num >> 16) + amt

            if (r > 255) r = 255
            else if (r < 0) r = 0

            var b = ((num >> 8) & 0x00ff) + amt

            if (b > 255) b = 255
            else if (b < 0) b = 0

            var g = (num & 0x0000ff) + amt

            if (g > 255) g = 255
            else if (g < 0) g = 0

            return (usePound ? '#' : '') + (g | (b << 8) | (r << 16)).toString(16)
          }

          /**
           * Model by Tomás Laulhé (https://www.patreon.com/quaternius), modifications by Don McCurdy (https://donmccurdy.com)
           * https://threejs.org/examples/#webgl_animation_skinning_morph
           * CC-0 license
           */
          this.third.load.gltf('/assets/glb/robot.glb').then(gltf => {
            this.robot = new ExtendedObject3D()
            this.robot.add(gltf.scene)

            this.robot.traverse(child => {
              if (child.isMesh) {
                child.castShadow = child.receiveShadow = true
                if (child.material.isMaterial) {
                  const color = new THREE.Color(child.material.color).getHexString()
                  // lighten color by 10%
                  const newColor = new THREE.Color(LightenDarkenColor(`#${color}`, 10))
                  // add new standard material with metallic look
                  child.material = this.third.add.material({
                    standard: { color: newColor, emissive: newColor, roughness: 0.4, metalness: 1, skinning: true }
                  })
                  child.material.needsUpdate = true
                }
              }
            })

            this.robot.position.set(0, -2, 0)
            this.third.add.existing(this.robot)

            // add idle animation
            this.third.animationMixers.add(this.robot.animation.mixer)
            this.robot.animation.add(
              'Idle',
              gltf.animations.find(anim => anim.name === 'Idle')
            )
            this.robot.animation.play('Idle')
          })
        }
      }

      const config = {
        type: Phaser.WEBGL,
        transparent: true,
        scale: {
          mode: Phaser.Scale.FIT,
          autoCenter: Phaser.Scale.CENTER_BOTH,
          width: window.innerWidth * Math.max(1, window.devicePixelRatio / 2),
          height: window.innerHeight * Math.max(1, window.devicePixelRatio / 2)
        },
        scene: [MainScene],
        ...Canvas()
      }

      window.addEventListener('load', () => {
        enable3d(() => new Phaser.Game(config)).withPhysics('/lib/ammo/kripken')
      })
    </script>
  </body>
</html>
